<?php

namespace app\api\controller;

use app\api\model\Wxapp as WxappModel;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\library\wechat\WxPay;
use think\Cache;
use think\Db;
use app\common\service\Order as OrderService;
use app\api\service\orderanswer\PaySuccess;
use app\common\enum\order\PayType as PayTypeEnum;

/** 问答类 */
class Beganswer extends Controller
{
    /** 获取该试卷的信息 */
    public function getQaBoxInfo()
    {
        $paramArr = $this->request->param();
        $buyid = $paramArr['buyid'];

        $buyInfo = Db::name('qa_buyquestion')->where('buy_id', $buyid)->find();

        $perKaoObj = array();
        // 0. 先查找一下本试卷是否存在还没有结束的考试，如果存在未结束的考试，则继续上次的考试
        $lastKsObj = Db::name('qa_answerlog')->where(['ex_uid'=>$buyInfo['buy_uid'], 'ex_buyid'=>$buyid, 'ex_is_allover'=>0])->find();
        if(isset($lastKsObj['ex_id'])){
            $perKaoObj = $lastKsObj;
        }
        else{
            // 查找此套试卷信息
            $boxInfo = Db::name('qa_boxquestion')->where('bq_id', $buyInfo['buy_qa_id'])->find();
            // 将此试卷的所有题目随机打乱做成本次考试
            $list = Db::name('qa_perquestion')->where(['pq_pid'=>$buyInfo['buy_qa_id'], 'pq_show'=>1])->orderRaw("RAND()")->select()->toArray();
            if(count($list)==0){
                return $this->renderError('该试卷还没录入任何考题');
            }
            else{
                $randIdArr = array();
                foreach ($list as $value) {
                    $randIdArr[] = $value['pq_id'];
                }
                // 1. 每次初始化，做到试卷题目随机，答案随机
                $inArr['ex_buyid'] = $buyid;
                $inArr['ex_uid'] = $buyInfo['buy_uid'];
                $inArr['ex_unick'] = $buyInfo['buy_unick'];
                $inArr['ex_uheader'] = $buyInfo['buy_uheader'];
                $inArr['ex_qa_id'] = $boxInfo['bq_id'];
                $inArr['ex_qa_title'] = $boxInfo['bq_title'];
                $inArr['ex_qa_price'] = $boxInfo['bq_price'];
                $inArr['ex_qa_des'] = $boxInfo['bq_des'];
                $inArr['ex_easy'] = $boxInfo['bq_easy'];
                $inArr['ex_init_ids'] = implode(',', $randIdArr);
                $inArr['ex_answer_num'] = 0;
                $inArr['ex_qa_num'] = count($list);
                $inArr['ex_per_score'] = floor(100/count($list));   //每道题的得分，不是积分是得分，每套题满分100分
                $bq_down_money = $boxInfo['bq_down_money'];
                //$inArr['ex_one_tojifen'] = floor($inArr['ex_per_score']*($boxInfo['bq_price'] - $bq_down_money)); //1元平台服务费 1元=100积分，每得1分奖励1积分，8元=800积分，每得1分奖励8积分
                $inArr['ex_one_tojifen'] = floor(($buyInfo['buy_qa_price']*100)/count($list));
                $inArr['ex_all_seconds'] = 50*60; // 每次考试50分钟
                $inArr['ex_last_seconds'] = 50*60*1000; // 前端倒计时需要的系统，暂未用到，目前每个题设置5分钟
                $inArr['ex_beg_time'] = time();
                $inArr['ex_stop_time'] = time()+1;
                $inArr['ex_is_allover'] = 0;
                $inArr['ex_answered_ids'] = "";
                $inArr['ex_answered_idslog'] = "";
                $inArr['wxapp_id'] = $boxInfo['wxapp_id'];
                $inArr['ex_addtime_str'] = date('Y-m-d H:i:s',time());
                $exid = Db::name('qa_answerlog')->insertGetId($inArr);
                $perKaoObj = $inArr;
                $perKaoObj['ex_id'] = $exid;
                // 2. 修改用户的试卷状态，每次开始新的考试的时候执行
                $upArr['buy_answer_num'] = 0;
                $upArr['buy_qa_num'] = count($list);
                $upArr['box_status'] = 3;
                $upArr['buy_answer_isover'] = 0;
                Db::name('qa_buyquestion')->where('buy_id',$buyid)->update($upArr);
            }
        }
        return $this->renderSuccess(compact('buyInfo', 'perKaoObj'));
    }

    /** 获取每个题目的具体信息，目前逻辑是首次进入界面请求第一个考题 */
    public function getPerQuestion(){
        $paramArr = $this->request->param();
        $exid = $paramArr['exid'];

        $kaoshiObj = Db::name('qa_answerlog')->where('ex_id', $exid)->find();

        $perQuestion = $this->getNextPerQuestion($kaoshiObj['ex_init_ids'],$kaoshiObj['ex_answer_num']);

        return $this->renderSuccess(compact('kaoshiObj','perQuestion'));
    }

    /**提交本次答案，并显示下一题，携带答案的提交 */
    public function submitDaAn(){
        $paramArr = $this->request->param();
        $exid = $paramArr['exid'];
        $daanStr = trim($paramArr['daanStr']);
        // 本次靠卷信息obj
        $kaoshiObj = Db::name('qa_answerlog')->where('ex_id', $exid)->find();
        $nowdbAnswerNum = $kaoshiObj['ex_answer_num'];  // 提交第一题为0，提交第二题为1
        // 提交答案的时候，判断目前回几个问题了，判断是否结束
        $isOver = $nowdbAnswerNum == $kaoshiObj['ex_qa_num'] ? true : false;

        // 判断是否已经结束考试
        if($isOver==true){
            return $this->renderError('该此考试已结束，请勿重复点击');
        }
        // 如果考试还没有结束，则进行下一题
        else{
            // 当前提交的是否为最后一题
            $isLast = $nowdbAnswerNum+1==$kaoshiObj['ex_qa_num'] ? true : false;
            // 本次回答的考题
            $nowQuetionObj = $this->getNextPerQuestion($kaoshiObj['ex_init_ids'], $nowdbAnswerNum);
            // 如果是多选题，先将多选的答案排序保持一致再进行比较，别忘记处理，前端组转已处理过
            $isRight = trim($nowQuetionObj['pq_right'])==$daanStr ? true : false;

            // 1. 判断本次回答的是否正确，修改本次kaoshiObj中的ex_answer_num加1，已回答的问题ids集合ex_answered_ids，以及本次回答是否正确的集合
            $upArr111['ex_answer_num'] = $nowdbAnswerNum+1;
            // 1.1 将已回答的单题id加入队列
            $nowAnswerIdsArr = explode(',', $kaoshiObj['ex_answered_ids']);
            $nowAnswerIdsArr[] = $nowQuetionObj['pq_id'];
            $upArr111['ex_answered_ids'] = trim(implode(',', $nowAnswerIdsArr),',');
            // 1.2 将该单题回答是否正确加入队列
            $isRightArr = explode(',', $kaoshiObj['ex_answered_idslog']);
            $isRightArr[] = $isRight==true ? 1 : 0;
            $upArr111['ex_answered_idslog'] = trim(implode(',', $isRightArr),',');
            $upArr111['ex_is_allover'] = $isLast==true ? 1 : 0;
            $upArr111['ex_stop_time'] = time(); // 每提交一次答案，计算一下剩余时间
            $rightNum = 0;
            if($isLast==true){
                $rightNum = $this->getRightNum($isRightArr);
                $upArr111['ex_get_allkaofen'] = $kaoshiObj['ex_per_score']*$rightNum;
                $upArr111['ex_get_alljifen'] = $kaoshiObj['ex_one_tojifen']*$rightNum;
            }
            Db::name('qa_answerlog')->where('ex_id',$exid)->update($upArr111);

            // 2. 修改qa_buyquestion中最后一次答题的数据记录，buy_answer_num，buy_answer_isover
            $upArr222['buy_answer_num'] = $nowdbAnswerNum+1;
            $upArr222['buy_qa_num'] = $kaoshiObj['ex_qa_num'];
            $upArr222['buy_answer_isover'] = $isLast==true ? 1 : 0;
            Db::name('qa_buyquestion')->where('buy_id',$kaoshiObj['ex_buyid'])->update($upArr222);

            $tipArr['isover'] = 'no';
            $tipArr['rightNum'] = $rightNum;
            $tipArr['getScore'] = 0;
            $tipArr['getJiFen'] = 0;
            $tipArr['isRight'] = $isRight==true ? 'yes' : 'no';
            $tipArr['passRightDaan'] = trim($nowQuetionObj['pq_right']);
            // 3. 展示给前端
            if($isLast==true){
                $kaoshiObj['ex_answer_num'] = $kaoshiObj['ex_answer_num'];
                $perQuestion = null;

                // 提交了最后一体答案，考试结束，执行考试结束后的逻辑
                $backArr = $this->testOver($kaoshiObj,$isRightArr);
                $tipArr['getScore'] = $rightNum*$kaoshiObj['ex_per_score'];
                $tipArr['getJiFen'] = $backArr['chaJifen'];
            }
            else{
                $kaoshiObj['ex_answer_num'] = $nowdbAnswerNum+1;
                $perQuestion = $this->getNextPerQuestion($kaoshiObj['ex_init_ids'],$nowdbAnswerNum+1);
            }
        }
        return $this->renderSuccess(compact('kaoshiObj','perQuestion', 'tipArr'));
    }

    /** 根据本次考卷id，获得当前展示下一个考题 */
    private function getNextPerQuestion($kaoshiObjIDS, $nowAnswerCnt){
        // 根据当前进行到第几个题，选择下一题的id;
        $ex_init_idsArr = explode(',', $kaoshiObjIDS);   //所有的考题ids数组

        // 下一题的试题id是多少
        $perqustionid = $ex_init_idsArr[$nowAnswerCnt];
        $perQuestion = Db::name('qa_perquestion')->where('pq_id', $perqustionid)->find();
        return $perQuestion;
    }

    /** 考试结束的处理函数 */
    private function testOver($kaoshiObj, $isRightArr){
        // 2.1 设置box_use_num+=1
        $sql = "update ".getTable('qa_buyquestion')." set box_use_num=box_use_num+1 where buy_id=".$kaoshiObj['ex_buyid'];
        Db::query($sql);
        // 2.2 计算该试卷的平均得分，以及已经获得的积分
        $buyQaObj = Db::name('qa_buyquestion')->where('buy_id', $kaoshiObj['ex_buyid'])->find();
        $rightNum = $this->getRightNum($isRightArr);
        $thisGetAllFen = $kaoshiObj['ex_per_score']*$rightNum;
        $thisGetAllJifen = $kaoshiObj['ex_one_tojifen']*$rightNum;
        $pastFen = $buyQaObj['ans_money_score'];    // 已经得到的分
        $pastJifen = $buyQaObj['ans_money_jifen'];
        $pastPinJun = $buyQaObj['ans_average_score'];  //处理第一次答卷平均分
        // 只有本次得分比上次高，才会补差分
        $chaFen = $thisGetAllFen > $pastFen ? $thisGetAllFen-$pastFen : 0;
        $chaJifen = $thisGetAllJifen > $pastJifen ? $thisGetAllJifen-$pastJifen : 0;
        // 只有上次成绩和本次成绩大于0，才做平均分统计，否则平均分不变
        $chushu = $pastPinJun>0 ? 2 : 1;
        $pinJunScore = $thisGetAllFen>0 ? floor(($pastPinJun+$thisGetAllFen)/$chushu) : $pastPinJun;
        $upArr111['ans_average_score'] = $pinJunScore;

        if($thisGetAllFen > $pastFen){
            $upArr111['ans_money_score'] = $thisGetAllFen;
            $upArr111['ans_money_jifen'] = $thisGetAllJifen;
        }
        Db::name('qa_buyquestion')->where('buy_id',$kaoshiObj['ex_buyid'])->update($upArr111);
        // 给用户发放本次考试差额积分。
        if($chaJifen > 0){
            $sql22 = "update ".getTable('user')." set points=points+$chaJifen , allsend_points=allsend_points+$chaJifen where user_id=".$kaoshiObj['ex_uid'];
            Db::query($sql22);
            $upArr222['user_id'] = $kaoshiObj['ex_uid'];
            $upArr222['value'] = $chaJifen;
            $upArr222['describe'] = "答题获得".$chaJifen."积分";
            $upArr222['remark'] = "用户".$kaoshiObj['ex_unick']."答题获得".$chaJifen."积分";
            $upArr222['wxapp_id'] = $kaoshiObj['wxapp_id'];
            $upArr222['create_time'] = time();
            Db::name('user_points_log')->insert($upArr222);
        }
        $back['chaJifen'] = $chaJifen;
        return $back;
    }
    /** 通过isright数组，统计回答正确的个数 */
    private function getRightNum($isRightArr)
    {
        $rightNum = 0;
        // 此次答题一共做对了多少题
        foreach ($isRightArr as $value) {
            if($value==1){
                $rightNum++;
            }
        }
        return $rightNum;
    }
}
